package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.PageResult;
import com.hmall.search.pojo.SearchParam;
import com.hmall.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestHighLevelClient client;

    @Value("${indexStr}")
    private String indexStr;

    @Override
    public List<String> findItemBySuggestionKey(String key) {
        if (StringUtils.isBlank(key)){
            return null;
        }
        List<String> list = new ArrayList<>();
        SearchRequest request = new SearchRequest(indexStr);
        request.source().suggest(
                new SuggestBuilder().addSuggestion(
                        "mysuggestion",
                        SuggestBuilders.completionSuggestion("suggestion")
                                .skipDuplicates(true)
                                .size(10)
                                .prefix(key)
                )
        );
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            CompletionSuggestion completionSuggestion = response.getSuggest().getSuggestion("mysuggestion");
            List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getOptions();
            for (CompletionSuggestion.Entry.Option option : options) {
                String str = option.getText().toString();
                list.add(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public Map<String, List<String>> filter(SearchParam searchParam) {
        //校验参数
        if (ObjectUtils.isNull(searchParam)){
            throw new RuntimeException("传参错误");
        }
        //创建搜索请求对象
        SearchRequest request = new SearchRequest(indexStr);
        boolQuery(searchParam,request);

        List<String> brandList = getKeyList(request, "brand", "brandAgg");
        List<String> categoryList = getKeyList(request, "category", "categoryAgg");

        Map<String,List<String>> resultMap = new HashMap<>();
        resultMap.put("brand",brandList);
        resultMap.put("category",categoryList);

        return resultMap;
    }

    @Override
    public PageResult<ItemDoc> findItemByParam(SearchParam searchParam) {
        //校验参数
        if (ObjectUtils.isNull(searchParam)){
            throw new RuntimeException("传参错误");
        }
        //创建搜索请求对象
        SearchRequest request = new SearchRequest(indexStr);
        boolQuery(searchParam,request);
        requestSortAndPage(searchParam,request);

        PageResult<ItemDoc> result = new PageResult<>();
        try {
            //执行请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //请求返回数据处理
            long total = response.getHits().getTotalHits().value;
            ArrayList<ItemDoc> itemDocs = new ArrayList<>();
            SearchHit[] hits = response.getHits().getHits();
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                Object[] sortValues = hit.getSortValues();
                ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
                itemDocs.add(itemDoc);
            }

            result.setList(itemDocs);
            result.setTotal(total);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private List<String> getKeyList(SearchRequest request,String field,String aggName) {
        request.source().aggregation(AggregationBuilders.terms(aggName)
                .field(field)
                .size(20));
        ArrayList<String> stringList = new ArrayList<>();
        try {
            //执行请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Aggregations aggregations = response.getAggregations();
            Terms terms = aggregations.get(aggName);
            List<? extends Terms.Bucket> buckets = terms.getBuckets();
            for (Terms.Bucket bucket : buckets) {
                String keyAsString = bucket.getKeyAsString();
                stringList.add(keyAsString);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringList;
    }

    public void boolQuery(SearchParam searchParam,SearchRequest request){
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (StringUtils.isBlank(searchParam.getKey())){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            boolQuery.must(QueryBuilders.matchQuery("all",searchParam.getKey()));
        }
        if (ObjectUtils.isNotNull(searchParam.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand",searchParam.getBrand()));
        }
        if (ObjectUtils.isNotNull(searchParam.getCategory())){
            boolQuery.filter(QueryBuilders.termQuery("category",searchParam.getCategory()));
        }
        if (ObjectUtils.isNotNull(searchParam.getMaxPrice())&&ObjectUtils.isNotNull(searchParam.getMinPrice())){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gt(searchParam.getMinPrice())
                    .lte(searchParam.getMaxPrice()));
        }

        FunctionScoreQueryBuilder functionScoreQuery = new FunctionScoreQueryBuilder(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(100.0F)
                        )
                }
        ).boostMode(CombineFunction.MULTIPLY);

        request.source().query(functionScoreQuery);
    }

    public void requestSortAndPage(SearchParam searchParam,SearchRequest request){
        request.source().from((searchParam.getPage()-1)*searchParam.getSize());
        request.source().size(searchParam.getSize());
        if ("price".equals(searchParam.getSortBy())){
            request.source().sort(searchParam.getSortBy(), SortOrder.ASC);
        }else if ("sold".equals(searchParam.getSortBy())){
            request.source().sort(searchParam.getSortBy(), SortOrder.DESC);
        }
    }
}
